package com.ruoyi.dingtalk;

import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.*;
import com.dingtalk.api.response.*;
import com.ruoyi.common.exception.CustomException;
import com.ruoyi.web.core.config.DingTalkConfig;
import com.taobao.api.ApiException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 钉钉用户接口
 *
 * @author YW
 */
@Component
public class DingTalkUserService {

    @Autowired
    private DingTalkConfig dingTalkConfig;

    /**
     * 获取token信息
     */
    public String getAccessToken() {
        DefaultDingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/gettoken");
        OapiGettokenRequest request = new OapiGettokenRequest();
        request.setAppkey(dingTalkConfig.getAppKey());
        request.setAppsecret(dingTalkConfig.getAppSecret());
        request.setHttpMethod("GET");
        try {
            OapiGettokenResponse response = client.execute(request);
            return response.getAccessToken();
        } catch (ApiException e) {
            throw new CustomException("获取用户信息出错：获取token异常！", e);
        }
    }

    public OapiV2UserGetResponse.UserGetResponse getUserInfo(String authCode) {
        String accessToken = this.getAccessToken();
        try {
            DingTalkClient dingTalkClient = new DefaultDingTalkClient("https://oapi.dingtalk.com/user/getuserinfo");
            OapiUserGetuserinfoRequest request = new OapiUserGetuserinfoRequest();
            request.setCode(authCode);
            request.setHttpMethod("GET");
            OapiUserGetuserinfoResponse response = dingTalkClient.execute(request, accessToken);
            String userId = response.getUserid();
            return getUserInfoByUserId(accessToken, userId);
        } catch (ApiException e) {
            throw new CustomException("获取用户信息出错：根据authCode获取用户信息失败！", e);
        }
    }

    private OapiV2UserGetResponse.UserGetResponse getUserInfoByUserId(String accessToken, String userId) throws ApiException {
        DingTalkClient clientDingTalkClient2 = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/user/get");
        OapiV2UserGetRequest reqGetRequest = new OapiV2UserGetRequest();
        reqGetRequest.setUserid(userId);
        reqGetRequest.setLanguage("zh_CN");
        OapiV2UserGetResponse rspGetResponse = clientDingTalkClient2.execute(reqGetRequest, accessToken);
        return rspGetResponse.getResult();
    }

    /**
     * 根据授权码获取用户信息
     *
     * @param code 临时授权码
     */
    public OapiV2UserGetResponse.UserGetResponse getUserInfoByCode(String code) {
        try {
            String accessToken = this.getAccessToken();
            // 通过临时授权码获取授权用户的个人信息
            DefaultDingTalkClient client2 = new DefaultDingTalkClient("https://oapi.dingtalk.com/sns/getuserinfo_bycode");
            OapiSnsGetuserinfoBycodeRequest reqBycodeRequest = new OapiSnsGetuserinfoBycodeRequest();
            // 通过扫描二维码，跳转指定的redirect_uri后，向url中追加的code临时授权码
            reqBycodeRequest.setTmpAuthCode(code);
            OapiSnsGetuserinfoBycodeResponse bycodeResponse = client2.execute(reqBycodeRequest, dingTalkConfig.getAppKey(), dingTalkConfig.getAppSecret());

            // 根据unionid获取userid
            String unionid = bycodeResponse.getUserInfo().getUnionid();
            DingTalkClient clientDingTalkClient = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/user/getbyunionid");
            OapiUserGetbyunionidRequest reqGetbyunionidRequest = new OapiUserGetbyunionidRequest();
            reqGetbyunionidRequest.setUnionid(unionid);
            OapiUserGetbyunionidResponse oapiUserGetbyunionidResponse = clientDingTalkClient.execute(reqGetbyunionidRequest, accessToken);
            // 根据userId获取用户信息
            String userid = oapiUserGetbyunionidResponse.getResult().getUserid();
            DingTalkClient clientDingTalkClient2 = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/user/get");
            OapiV2UserGetRequest reqGetRequest = new OapiV2UserGetRequest();
            reqGetRequest.setUserid(userid);
            reqGetRequest.setLanguage("zh_CN");
            OapiV2UserGetResponse rspGetResponse = clientDingTalkClient2.execute(reqGetRequest, accessToken);
            return rspGetResponse.getResult();
        } catch (ApiException e) {
            throw new CustomException("获取用户信息出错：根据临时授权码获取用户信息失败！", e);
        }
    }

}
